// ---------------------------------------------------------------------------
//Copyright (C) 2008-2011 Nokia Corporation and/or its subsidiary(-ies).
//All rights reserved.
//Contact: Nokia Corporation (qt-info@nokia.com)

//You may use the files in this folder under the terms of the BSD
//license as follows:

//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are
//met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//  * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
//    the names of its contributors may be used to endorse or promote
//    products derived from this software without specific prior written
//    permission.

//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
//OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// ---------------------------------------------------------------------------

.pragma library

var _db;

function openDB() {
    _db = openDatabaseSync("KarmaDB","1.0","The Karma Way Database",1000000);
    createTable();
    createUser();
    if (countUsers()==0)
        createDefaultUser();
}

function createTable(){
    _db.transaction(
                function(tx){
                    tx.executeSql("CREATE TABLE IF NOT EXISTS karma (id INTEGER PRIMARY KEY AUTOINCREMENT, points INTEGER, title TEXT, modified TEXT)");
                }
                )
}


function dropKamraTable()
{
    _db.transaction(
                function(tx){
                    tx.executeSql("DROP TABLE IF EXISTS karma");
                }
                )
}

function readKarmas()
{
    var data = [];
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT * FROM karma ORDER BY modified DESC");
                    for (var i=0; i< rs.rows.length; i++) {
                        data[i] = rs.rows.item(i);
                    }

                }
                )
    return data;
}

function updateKarma(karmaItem)
{
    _db.transaction(
                function(tx){
                    tx.executeSql("UPDATE karma SET points = ? ,  \
                                  title = ?,  modified = ?  \
                                  WHERE id = ?", [karmaItem.points,  karmaItem.title,
                                                  karmaItem.modified, karmaItem.id]);
                }
                )
}


function deleteKarma(id)
{
    _db.transaction(
                function(tx){
                    tx.executeSql("DELETE FROM karma WHERE id = ?", id);
                }
                )
}

function createKarma(karmaItem)
{   
    //print ('creating karma record:' + karmaItem.title + ' ' +karmaItem.points)
    _db.transaction(
                function(tx){
                    tx.executeSql("INSERT INTO karma (points,title, modified) VALUES(?,?,?)",[ karmaItem.points, karmaItem.title, karmaItem.modified]);
                }
                )
}


function readKarmaList(model)
{
    model.clear()
    //print ('reading karma list')
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT * FROM karma ORDER BY modified DESC");
                    for (var i=0; i< rs.rows.length; i++) {
                        model.append(rs.rows.item(i))
                    }
                }
                )
}

function getGoodKarma()
{
    var data=0
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT SUM(points) AS good FROM karma WHERE points>0");
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0).good
                        //print (data)
                    }
                }
                )
    return data;
}

function getBadKarma()
{
    var data=0
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT SUM(points) AS bad FROM karma WHERE points<0");
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0).bad
                    }
                }
                )
    return data;
}

function readKarmaItem(karmaId) {
    var data
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT * FROM karma WHERE id=?", [karmaId])
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0)
                    }
                }
                )
    return data;
}


function createUser(){
    _db.transaction(
                function(tx){
                    tx.executeSql("CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT, image TEXT)");
                }
                )
}


function createDefaultUser()
{
    //print ('creating karma record:' + karmaItem.title + ' ' +karmaItem.points)
    _db.transaction(
                function(tx){
                    tx.executeSql("INSERT INTO user (id,name, image) VALUES(1,\"Your name\",\"qrc:/violet/face\")");
                }
                )
}

function updateUser(UserItem)
{
    _db.transaction(
                function(tx){
                    tx.executeSql("UPDATE user SET name = ? ,  image = ?  \
                                  WHERE id = ?", [UserItem.name,  UserItem.image, UserItem.id]);
                }
                )
}

function readUserItem(userId) {
    var data
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT * FROM user WHERE id=?", [userId])
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0)
                    }
                }
                )
    return data;
}

function countUsers() {
    var data=0
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT COUNT(*) AS number FROM user")
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0).number
                    }
                }
                )
    return data;
}

function printObject(o)
{
    print('---')
    print(Object.keys(o))
    for(var key in o) {
        print("  " + key +"="+o[key])
    }

}
/*
function countBox(boxId)
{
    var data = 0;
    _db.readTransaction(
                function(tx){
                    var rs = tx.executeSql("SELECT count(*) FROM todo WHERE box = ?",[boxId]);
                    if(rs.rows.length === 1) {
                        data = rs.rows.item(0)["count(*)"]
                    }

                }
                )
    return data;
}

function createBatchTodos(data)
{
    _db.transaction(
                function(tx){
                    for(var i=0; i<data.length; i++) {
                        var item = data[i]
                        tx.executeSql("INSERT INTO todo (box, done, title, note, modified) VALUES(?,?,?,?,?)",[item.box, item.done, item.title, item.note, item.modified]);
                    }
                }
                )
}

function clearArchive(model)
{
    model.clear()
    _db.transaction(
                function(tx){
                    tx.executeSql("DELETE FROM karma WHERE box = 4");
                }
                )
}
function updateArchive(box)
{
    _db.transaction(
                function(tx){
                    tx.executeSql("UPDATE todo SET box = 4 WHERE done = 'true' AND box=?",box);
                }
                )
}

*/
function defaultItem()
{
    return {points: 0, title: "", modified: new Date()}
}

function defaultUserItem()
{
    return {id: 1, name: "", image: ""}
}
